package com.example.pay.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;

/**
 * 直接使用内嵌 JSON 数据进行验签，不读文件。
 * 运行前可设置环境变量 MERCHANT_CERT_PATH 指向商户证书（或使用默认 classpath:apiclient_cert.pem）。
 */
public class AppPaySignVerifyDirectRunner {

    // 将待验证的 JSON 数据直接粘贴到此处
    private static final String JSON = "{\n" +
            "     \"channel\": \"WECHAT\",\n" +
            "     \"orderCode\": \"KRPDUL8CXW0M910Q3JTGM5DMK1UFQEOG\",\n" +
            "     \"payload\": {\n" +
            "         \"timeStamp\": \"1762850008\",\n" +
            "         \"package\": \"Sign=WXPay\",\n" +
            "         \"paySign\": \"oCDVsEabUTueIqD1gqcFrVAm7tyLnf4sxkyNw4214B14rtl4wyq85eihywPQ2+cvrEF7QgGXy0nH+cChYVEcln1Is7uephNAbg3xzt577P/x2WZ6vAt3xjZPON56AJeK1fjTpJw0hKxTmwdxdZ4bxyv6PMhj88kzo0U4joxF+SdQS7GGGn2BYGJe7FrMIxEhLFWlRNR1Ky4dZmFhYEYZSwLqw1WIC7IUgRlJY5a8QPruCckNdy42QKqrZJdbTNvYmfCnDcm140QyBS/vbXzJ1QFtSMG5V/j2Qq/UdcrJh/D6ZkE/KwjMRjYknaKNStFb/2jMrG3r1iN+rthenW3Dng==\",\n" +
            "         \"appId\": \"wx73e3b92304c8bf28\",\n" +
            "         \"signType\": \"RSA\",\n" +
            "         \"partnerId\": \"1604511562\",\n" +
            "         \"prepayId\": \"wx111633288679559720cf6b9d64aa340000\",\n" +
            "         \"nonceStr\": \"fe3da52c57ce44a9af75a3bf4ae6ca90\"\n" +
            "     }\n" +
            " }";

    public static void main(String[] args) throws Exception {
        String certPath = System.getenv("MERCHANT_CERT_PATH");
        if (certPath == null || certPath.isEmpty()) {
            certPath = "src/main/resources/derived_pub_key.pem"; // 默认使用派生公钥，确保与私钥配对
        }

        PublicKey pubKey = WeChatAppPaySignVerifier.loadPublicKeyFromPem(certPath);

        // 解析 JSON，打印尝试的签名串
        ObjectMapper mapper = new ObjectMapper();
        JsonNode root = mapper.readTree(JSON.getBytes(StandardCharsets.UTF_8));
        JsonNode payload = root.path("payload");
        String appId = payload.path("appId").asText();
        String partnerId = payload.path("partnerId").asText();
        String prepayId = payload.path("prepayId").asText();
        String nonceStr = payload.path("nonceStr").asText();
        String timeStamp = payload.path("timeStamp").asText();
        String paySign = payload.path("paySign").asText();

        String v1 = WeChatAppPaySignVerifier.buildSignString(appId, partnerId, prepayId, nonceStr, timeStamp);
        String v2 = new StringBuilder()
                .append("appid=").append(appId)
                .append("&partnerid=").append(partnerId)
                .append("&prepayid=").append(prepayId)
                .append("&package=Sign=WXPay")
                .append("&noncestr=").append(nonceStr)
                .append("&timestamp=").append(timeStamp)
                .toString();
        String v3 = "appid=" + appId + "&noncestr=" + nonceStr + "&package=Sign=WXPay&partnerid=" + partnerId + "&prepayid=" + prepayId + "&timestamp=" + timeStamp;

        // v3 App 调起支付官方换行签名串（注意末尾仍需一个换行）
        String appV3Newline = appId + "\n" + timeStamp + "\n" + nonceStr + "\n" + prepayId + "\n";
        System.out.println("尝试签名串 app-v3(换行): " + appV3Newline.replace("\n", "\\n"));
        boolean rAppV3 = WeChatAppPaySignVerifier.verify(appV3Newline, paySign, pubKey);
        System.out.println("app-v3(换行) 验签：" + (rAppV3 ? "通过" : "失败"));
        System.out.println("最终验签结果：" + ((rAppV3 ) ? "通过" : "失败"));
    }
}